package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.DestinationQuery;
import cn.wolfcode.luowowo.repository.DestinationRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class DestinationServiceImpl implements IDestinationService{

    @Autowired
    private DestinationRepository destinationRepository;

    @Autowired
    private IRegionService regionService;

    @Autowired
    private MongoTemplate template;
    @Override
    public void save(Destination destination) {
        destinationRepository.save(destination);
    }

    @Override
    public void delete(String id) {
        destinationRepository.deleteById(id);
    }

    @Override
    public void update(Destination destination) {

    }

    @Override
    public Destination get(String id) {
        Optional<Destination> optional = destinationRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Destination> list() {
        return destinationRepository.findAll();
    }

    @Override
    public List<Destination> getDestByRegionId(String rid) {
        //通过区域id得到改区域，然后得到该区域下的关联目的地id，最后查找出关联的目的地
        Region region = regionService.get(rid);
        List<String> refIds = region.getRefIds();
        //相当于sql：select * from dest where id in (refIds)  遵循jpa规范即可
        return destinationRepository.findByIdIn(refIds);
    }


    @Override
    public Page<Destination> query(DestinationQuery qo) {
        //判断请求中是否包含关键字或parentId，有就加入到查询条件对象中，parentId如果没有就
        //设为null，进行分页查询返回页面结果集对象
        Query query = new Query();
        if(StringUtils.hasLength(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(".*"+qo.getKeyword()+".*"));
        }

        if(StringUtils.hasLength(qo.getParentId())){
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else{
            query.addCriteria(Criteria.where("parentId").is(null));
        }
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,Destination.class,query,pageable);
    }

    @Override
    public List<Destination> getToasts(String parentId) {
        //parentId指点击的目的地id
        //如果当前城市id没有，则返回空的list集合，否则
        //得到上一级目的地，一直到上一级目的地parentId为null
        if(!StringUtils.hasLength(parentId)){
            return Collections.emptyList();
        }
        ArrayList<Destination> list = new ArrayList<>();
        createToast(list,parentId);
        Collections.reverse(list);
        return list;
    }

    @Override
    public List<Destination> queryByRegionIdForApi(String regionId) {
        //创建一个list集合装查询的目的地，根据reregionId查询出区域对象，然后
        //查询出区域对象关联的id，通过关联id查询出关联目的地，设置一级目的地和二级目的地
        // 的关系，最后存进list集合中
        List<Destination> list =null;
        if("-1".equals(regionId)){
            list=destinationRepository.findByParentName("中国");
        }else{
            Region region = regionService.get(regionId);
            List<String> refIds = region.getRefIds();
           list= destinationRepository.findByIdIn(refIds);
        }
        for(Destination destination:list){
            //为了页面好看点，只显示前5个
            PageRequest pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "_id");
            List<Destination> children=destinationRepository.findByParentId(destination.getId(),pageable);
            destination.setChildren(children);
        }
        return list;
    }

    @Override
    public Destination findByName(String name) {
        return destinationRepository.findByName(name);
    }

    private void createToast(List<Destination> list,String parentId){
        //循环得到查询的目的地  通过点击目的地id，得到目的地存放在list中
        Destination destination = this.get(parentId);
        list.add(destination);
        if(StringUtils.hasLength(destination.getParentId())){
            createToast(list,destination.getParentId());
        }
    }
}
